package com.wwwarehouse.common.custom_widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;

/**
 * Created by zhenwang.xiang on 2017/6/19.
 * Description:腾讯X5浏览器封装
 */

public class X5WebView extends LinearLayout implements View.OnClickListener {

    private ImageView mClose;
    private ImageView mRefresh;
    private TextView mTitle;
    private ProgressBar mProgressBar;
    private WebView mWebView;
    private Context mContext;
    private boolean isContentTitle = true;
    StateLayout mStateLayout = null;//状态页面的切换layout
    private boolean isFirst = false;

    public X5WebView(Context context) {
        this(context, null);
    }

    @SuppressWarnings("WrongConstant")
    public X5WebView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.X5WebView);
        int leftimage = typedArray.getResourceId(R.styleable.X5WebView_left_image, R.drawable.close);
        int rightimage = typedArray.getResourceId(R.styleable.X5WebView_right_image, R.drawable.refresh);
        String title = typedArray.getString(R.styleable.X5WebView_x5_title);
        int left_visible = typedArray.getInt(R.styleable.X5WebView_left_visible, 0);
        int right_visible = typedArray.getInt(R.styleable.X5WebView_right_visible, 0);
        int title_visible = typedArray.getInt(R.styleable.X5WebView_title_visible, 0);

        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.view_x5_webview, this, true);

        mClose = (ImageView) findViewById(R.id.img_close);
        mRefresh = (ImageView) findViewById(R.id.img_refresh);
        mTitle = (TextView) findViewById(R.id.title);
        mProgressBar = (ProgressBar) findViewById(R.id.progress);
        mWebView = (WebView) findViewById(R.id.webview);
        mStateLayout = (StateLayout) findViewById(R.id.content_state_id);
        mStateLayout.showEmptyView("请输入正确的网址", false);

        mClose.setImageResource(leftimage);
        mClose.setVisibility(left_visible);
        mRefresh.setImageResource(rightimage);
        mRefresh.setVisibility(right_visible);
        mTitle.setText(title);
        mTitle.setVisibility(title_visible);

        initWebViewSettings();
        setWebViewClient(false);
        setWebChromeClient();

        mClose.setOnClickListener(this);
        mRefresh.setOnClickListener(this);

        typedArray.recycle();


    }

    /**
     * 加载请求地址
     *
     * @param url 传进来跳转的网址
     */
    public void loadUrl(String url) {
        mStateLayout.showProgressView("正在加载网页", false);
        mWebView.loadUrl(url);
    }

    /**
     * 设置是否跳转到系统浏览器
     *
     * @param isjump 为true跳转到系统浏览器，false不跳转
     */
    private void setWebViewClient(final boolean isjump) {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return isjump;
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                mStateLayout.showNetworkView("网址不存在", false);
            }
        });
    }

    private void setWebChromeClient() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    mProgressBar.setVisibility(GONE);
                    mStateLayout.showContentView();
                    if (isFirst == false) {
                        mWebView.reload();
                        isFirst = true;
                    }
                } else {
                    if (mProgressBar.getVisibility() == GONE) {
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(webView, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView webView, String title) {
                super.onReceivedTitle(webView, title);
                if (isContentTitle) {
                    mTitle.setText(title);
                }
            }
        });
    }

    public WebView getWebView() {
        return mWebView;
    }

    private void initWebViewSettings() {
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    public void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            mTitle.setText(title);
        }
    }

    public void setTitle(int res) {
        mTitle.setText(res);
    }

    public void setContentTitle(boolean contenttitle) {
        isContentTitle = contenttitle;
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_close) {
            ((Activity) mContext).finish();
        } else if (i == R.id.img_refresh) {
            mWebView.reload();
        }
    }

}
